
package com.hlkj.pay.app.merchant.ext.impl.alipay.handler;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import javax.crypto.IllegalBlockSizeException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.FileItem;
import com.alipay.api.domain.ImgFile;
import com.alipay.api.request.AlipaySecurityRiskComplaintFileUploadRequest;
import com.alipay.api.request.AntMerchantExpandIndirectImageUploadRequest;
import com.alipay.api.response.AlipayOpenAuthTokenAppResponse;
import com.alipay.api.response.AlipaySecurityRiskComplaintFileUploadResponse;
import com.alipay.api.response.AntMerchantExpandIndirectImageUploadResponse;
import com.hlkj.framework.caches.service.RedisTemplateService;
import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.util.json.JsonUtils;
import com.hlkj.pay.app.merchant.IAcctAccountAppService;
import com.hlkj.pay.app.merchant.ext.MerchantExtConstant;
import com.hlkj.pay.app.merchant.ext.impl.alipay.constant.AliPayExtConstant;
import com.hlkj.pay.app.merchant.ext.impl.alipay.dto.AliPayChannelParams;
import com.hlkj.pay.app.merchant.ext.impl.alipay.dto.AlipayConfig;
import com.hlkj.pay.app.merchant.ext.impl.alipayZft.dto.AliPayZftChannelParams;
import com.hlkj.pay.app.merchant.ext.impl.wxpay.constant.ComplaintStatusType;
import com.hlkj.pay.common.PayResultCode;
import com.hlkj.pay.common.constants.RedisConstants;
import com.hlkj.pay.dto.merchant.MerchantAppQueryDto;
import com.hlkj.pay.dto.merchant.ProviderChannelFeeConfigList;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.enums.PayEnums;
import com.hlkj.pay.infrastructure.model.merchant.MerchantAppChannelDO;
import com.hlkj.pay.infrastructure.model.order.OrderComplaintChannelDO;
import com.hlkj.pay.infrastructure.model.order.PayOrderDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.service.merchant.IMerchantApplicationService;
import com.hlkj.pay.service.order.IPayOrderService;
import com.hlkj.pay.task.CommonTasks;
import com.hlkj.pay.util.ImageUtils;
import com.hlkj.pay.vo.openapi.fund.req.OpenApiFundAccountBindReq;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 支付宝服务商 商户进件参数处理
 *
 * @author HlpayTeam
 * @date 2024/09/26 12:02
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AliPayCommonParamsHandle {

    private final RedisTemplateService redisTemplateService;

    private final IMerchantApplicationService merchantApplicationService;

    private final IPayOrderService payOrderService;

    private final CommonTasks commonTasks;

    private final IAcctAccountAppService acctAccountAppService;

    @Value("${spring.profiles.active:}")
    private String active;


    public CommonResult<AlipayConfig> alipayConfig(String paramsConfig) {
        if (StringUtils.isEmpty(paramsConfig)) {
            return CommonResult.error(PayResultCode.PAY_CHANNEL_CONFIG_NOT_EXITS);
        }
        // 配置转换
        AlipayConfig alipayConfig = null;
        try {
            alipayConfig = JsonUtils.parseObject(paramsConfig, AlipayConfig.class);
            if(!active.equals("prod")){
                log.info("支付宝非prod 环境,更新证书信息");
                if(StrUtil.isNotEmpty(alipayConfig.getAlipayPublicCertPath())){
                    alipayConfig.setAlipayPublicCertPath(alipayConfig.getAlipayPublicCertPath().replace("/www/wwwroot/pay/uploads/secret/20241218/","E:\\work\\local_file\\secret\\20241217\\"));
                    alipayConfig.setRootCertPath(alipayConfig.getRootCertPath().replace("/www/wwwroot/pay/uploads/secret/20241218/","E:\\work\\local_file\\secret\\20241218\\"));
                    alipayConfig.setAppCertPath(alipayConfig.getAppCertPath().replace("/www/wwwroot/pay/uploads/secret/20241218/","E:\\work\\local_file\\secret\\20241218\\"));
                }
            }

            return CommonResult.success(alipayConfig);
        }
        catch (Exception e) {
            String format = String.format(PayResultCode.PAY_CHANNEL_CONFIG_ERROR.getMsg(), "支付宝");
            return CommonResult.error(PayResultCode.PAY_CHANNEL_CONFIG_NOT_EXITS.getCode(), format);
        }
    }

    public AlipayClient getAlipaClientByAppid(String appid) throws AlipayApiException {
        Object alipayObj = redisTemplateService.hGet(AliPayExtConstant.ALIPAY_APPID,appid);
        if(alipayObj == null){
            // 特约商户通道
            MerchantAppChannelDO merchantAppChannelDO = getMerchantAppChannelDO(appid);
            if(merchantAppChannelDO == null){
                return null;
            }
            CommonResult<AlipayConfig> commonResult = alipayConfig(merchantAppChannelDO.getAppConfigJson());
            if(!commonResult.isSuccess()){
                return null;
            }
            return initClient(commonResult.getData());
        }
        com.alipay.api.AlipayConfig alipayApiConfig = JSONUtil.toBean(JSONUtil.toJsonStr(alipayObj),com.alipay.api.AlipayConfig.class);
        // 存入redis
        redisTemplateService.hSet(AliPayExtConstant.ALIPAY_APPID,appid,alipayApiConfig,30*24*60*60);

        return new DefaultAlipayClient(alipayApiConfig);
    }

    public CommonResult<AlipayConfig> alipayConfig(ProviderChannelConfigDO providerChannelConfigDO, boolean test) {
        String paramsConfig = providerChannelConfigDO.getParamsConfig();
        if (StringUtils.isEmpty(paramsConfig)) {
            return CommonResult.error(PayResultCode.PAY_CHANNEL_CONFIG_NOT_EXITS);
        }
        // 配置转换
        AlipayConfig alipayConfig = null;
        try {
            alipayConfig = JsonUtils.parseObject(paramsConfig, AlipayConfig.class);
            if(!active.equals("prod")){
                log.info("支付宝非prod 环境,更新证书信息");
                if(StrUtil.isNotEmpty(alipayConfig.getAlipayPublicCertPath())){
                    alipayConfig.setAlipayPublicCertPath(alipayConfig.getAlipayPublicCertPath().replace("/www/wwwroot/pay/uploads/secret/20241218/","E:\\work\\local_file\\secret\\20241217\\"));
                    alipayConfig.setRootCertPath(alipayConfig.getRootCertPath().replace("/www/wwwroot/pay/uploads/secret/20241218/","E:\\work\\local_file\\secret\\20241218\\"));
                    alipayConfig.setAppCertPath(alipayConfig.getAppCertPath().replace("/www/wwwroot/pay/uploads/secret/20241218/","E:\\work\\local_file\\secret\\20241218\\"));
                }
            }

            return CommonResult.success(alipayConfig);
        }
        catch (Exception e) {
            String format = String.format(PayResultCode.PAY_CHANNEL_CONFIG_ERROR.getMsg(), "支付宝");
            return CommonResult.error(PayResultCode.PAY_CHANNEL_CONFIG_NOT_EXITS.getCode(), format);
        }
    }


    public AlipayClient initClient(AlipayConfig alipayConfig) throws AlipayApiException {
        com.alipay.api.AlipayConfig alipayApiConfig = new com.alipay.api.AlipayConfig();
        alipayApiConfig.setServerUrl(AliPayExtConstant.ALI_GATEWAY);
        alipayApiConfig.setAppId(alipayConfig.getAppId());
        alipayApiConfig.setPrivateKey(alipayConfig.getPrivateKey());
        alipayApiConfig.setFormat("json");
        alipayApiConfig.setAlipayPublicKey(alipayConfig.getPublicKey());
        alipayApiConfig.setCharset("UTF-8");
        alipayApiConfig.setSignType("RSA2");

        // 存入redis
        redisTemplateService.hSet(AliPayExtConstant.ALIPAY_APPID,alipayConfig.getAppId(),alipayApiConfig,30*24*60*60);

        return new DefaultAlipayClient(alipayApiConfig);
    }


    public FileItem getUploadFileItem(String filePath) {
        try {
            File file = null;
            if(HttpUtil.isHttp(filePath)  || HttpUtil.isHttps(filePath) ){
                // 创建临时文件
                file =  FileUtil.createTempFile("."+ ImageUtils.getFileExtension(filePath),true);
                // 文件流copy到临时文件
                HttpUtil.downloadFile(filePath,file);
            }else{
                file = FileUtil.newFile(filePath);
            }

            if(FileUtil.isEmpty(file)){
                log.error("支付宝 上传文件格式异常 ");
                throw new RuntimeException("支付宝 上传文件格式异常");
            }
            FileItem fileItem = new FileItem(file);
            return fileItem;
        } catch (Exception e) {
            log.error("支付宝 上传文件异常", e);
            throw new RuntimeException("支付宝 上传文件异常", e);
        }
    }


    public List<ImgFile> getComplaintImgUrls(List<String> imgs,AlipayConfig alipayConfig){
        List<ImgFile> imgFiles = new ArrayList<>();
        try{
            // 获取AlipayClient
            AlipayClient client = initClient(alipayConfig);
            for(String img:imgs){
                AlipaySecurityRiskComplaintFileUploadRequest request = new AlipaySecurityRiskComplaintFileUploadRequest();
                FileItem FileContent = getUploadFileItem(img);
                request.setFileContent(FileContent);

                log.info("支付宝投诉上传图片请求参数:{}", img);
                AlipaySecurityRiskComplaintFileUploadResponse response = client.execute(request);
                log.info("支付宝投诉上传图片返回参数:{}", JSONUtil.toJsonStr(response));

                if(response.isSuccess()){
                    ImgFile imgFile = new ImgFile();
                    imgFile.setImgUrl(response.getFileUrl());
                    imgFile.setImgUrlKey(response.getFileKey());
                    imgFiles.add(imgFile);
                }
            }
        }catch (Exception e){
            log.error("getComplaintImgUrls fail:{}",e);
        }
        return imgFiles;
    }


    /**
     * 判断是否普通商户
     * @param merchantAppChannelDO
     * @return
     */
    public boolean commonMer(MerchantAppChannelDO merchantAppChannelDO){
        boolean common = false;
        if(merchantAppChannelDO.getType() != null && MerchantEnum.APP_CHANNEL_TYPE.MERCHANT_COMMON.getCode()  == merchantAppChannelDO.getType()){
            common = true;
        }
        return common;
    }


    /**
     * 开通结算产品信息
     * @param merchantFeeConfigList  费率信息
     * @return
     */
    public String getSettleProductInfo(List<ProviderChannelFeeConfigList> merchantFeeConfigList){

        String rate = null;

        List<ProviderChannelFeeConfigList> settlementInfos = new ArrayList<>();

        // 支付类型分组
        Map<Integer, List<ProviderChannelFeeConfigList>> merchantFeeConfigMap = merchantFeeConfigList.stream()
                .filter(merchantFeeConfig -> merchantFeeConfig.getPayWayDO() != null)
                .collect(Collectors.groupingBy(merchantFeeConfig -> merchantFeeConfig.getPayWayDO().getType()));
        for (Map.Entry<Integer, List<ProviderChannelFeeConfigList>> entry : merchantFeeConfigMap.entrySet()) {
            switch (PayEnums.PAY_TYPE.fromByCode(entry.getKey())) {
                case FUNCTION:
                    for(ProviderChannelFeeConfigList feeConfig:entry.getValue()){
                        if(feeConfig.getStatus() == 1){
                            settlementInfos.add(feeConfig);
                        }
                    }
                    break;
            }

            // 结算费率
            if(CollUtil.isNotEmpty(settlementInfos)){
                // 过滤D0 只能选一种,按优先顺序取
                Optional<ProviderChannelFeeConfigList> feeConfig_OTHER = settlementInfos.stream().filter(conf -> Objects.equals(conf.getPayWayDO().getCode(),MerchantEnum.SETTLE_CYCLE.D0.getPayWayCode())).findFirst();
                // D0
                if(feeConfig_OTHER.isPresent()){
                    rate = feeConfig_OTHER.get().getDefaultFeeConfigValue().getRateBase().toString();
                }else{
                    // D1 默认固定值 0
                    feeConfig_OTHER = settlementInfos.stream().filter(conf -> Objects.equals(conf.getPayWayDO().getCode(),MerchantEnum.SETTLE_CYCLE.D1.getPayWayCode())).findFirst();
                    if(feeConfig_OTHER.isPresent()){
                        rate = feeConfig_OTHER.get().getDefaultFeeConfigValue().getRateBase().toString();
                    }else{
                        // T1
                        feeConfig_OTHER = settlementInfos.stream().filter(conf -> Objects.equals(conf.getPayWayDO().getCode(),MerchantEnum.SETTLE_CYCLE.T1.getPayWayCode())).findFirst();
                        if(feeConfig_OTHER.isPresent()){
                            rate = feeConfig_OTHER.get().getDefaultFeeConfigValue().getRateBase().toString();
                        }
                    }
                }
            }
        }

        // 默认服务费率（%），0.38~0.6 之间
        if(StrUtil.isEmpty(rate)){
            rate = "0.38";
        }
        if(Double.valueOf(rate) < 0.38 || Double.valueOf(rate) > 0.6){
            rate = "0.38";
        }
        return rate;
    }

    /**
     * 直付通上传图片
     * @param filePath
     * @param alipayConfig
     * @return
     */
    public String zftUploadImg(String filePath,AlipayConfig alipayConfig) {
        try {
            String imgType = FileUtil.extName(filePath);
            FileItem imageContent = getUploadFileItem(filePath);
            if(imageContent != null){
                // 初始化客户端
                AlipayClient alipayClient = initClient(alipayConfig);
                // 图片上传请求
                AntMerchantExpandIndirectImageUploadRequest request = new AntMerchantExpandIndirectImageUploadRequest();
                request.setImageContent(imageContent);
                request.setImageType(imgType);

                log.info("直付通上传图片 请求参数:{}", filePath);
                AntMerchantExpandIndirectImageUploadResponse response = alipayClient.execute(request);
                log.info("直付通上传图片 返回参数:{}", JsonUtils.toJsonString(response));

                if(response.isSuccess()){
                    log.info("直付通上传图片成功 返回参数:{}", response.getImageId());
                    return response.getImageId();
                }
                log.info("直付通上传图片失败 返回参数:{}", response.getSubMsg());
            }
            return null;
        } catch (Exception e) {
            log.error("支付宝直付通 上传文件异常", e);
            throw new RuntimeException("支付宝直付通 上传文件异常", e);
        }
    }

    /**
     * 获取特约商户通道
     * @param appId
     * @return
     */
    private MerchantAppChannelDO getMerchantAppChannelDO(String appId){
        MerchantAppQueryDto merchantAppQueryDto = new MerchantAppQueryDto();
        merchantAppQueryDto.setChannelCode(MerchantExtConstant.CHANNEL_ALI_PAY);
        merchantAppQueryDto.setType(1);
        List<MerchantAppChannelDO>  merchantAppChannelList = merchantApplicationService.queryChannelInfoList(merchantAppQueryDto);
        if(CollUtil.isEmpty(merchantAppChannelList) || merchantAppChannelList.size() > 1){
            log.info("alipay getMerchantAppChannelDO is null:{}",appId);
            return null;
        }
        if(merchantAppChannelList.size() > 1){
            log.info("alipay getMerchantAppChannelDO fail:{}, appid:{}",JSONUtil.toJsonStr(merchantAppChannelList),appId);
        }
        return merchantAppChannelList.get(0);
    }

    /**
     * 更新特约商户appAuthToken
     * @param authTokenAppResponse
     */
    public void updateAuthToken(AlipayOpenAuthTokenAppResponse authTokenAppResponse,String appId){
        MerchantAppChannelDO merchantAppChannelDO = getMerchantAppChannelDO(appId);
        if(merchantAppChannelDO != null){
            try{
                AliPayChannelParams oldChannelParams = JSONUtil.toBean(merchantAppChannelDO.getAppConfigJson(),AliPayChannelParams.class);
                if(oldChannelParams != null && oldChannelParams.getAppId().equals(appId)){
                    AliPayChannelParams newChannelParams = new AliPayChannelParams();
                    newChannelParams.setOpenId(oldChannelParams.getOpenId());
                    newChannelParams.setAppAuthToken(authTokenAppResponse.getAppAuthToken());
                    newChannelParams.setAppRefreshToken(authTokenAppResponse.getAppRefreshToken());
                    merchantApplicationService.updateAppConfig(merchantAppChannelDO,JSONUtil.toJsonStr(newChannelParams));
                    log.info("alipay updateAuthToken success old:{}, new:{}",JSONUtil.toJsonStr(merchantAppChannelDO),JSONUtil.toJsonStr(newChannelParams));
                }
            }
            catch (Exception e) {
                log.info("alipay updateAuthToken fail:{}",JSONUtil.toJsonStr(merchantAppChannelDO));
            }
        }
    }


    /**
     *
     *
     * 企业: 01
     * 事业单位: 02
     * 民办非企业组织: 03
     * 社会团体: 04
     * 党政及国家机关: 05
     * 个人商户: 06
     * 个体工商户: 07
     *
     * 系统主体类型
     *      * 1：政府机构
     *      * 2：国营企业
     *      * 3：私营企业
     *      * 4：外资企业
     *      * 5：个体工商户
     *      * 6：其它组织
     *      * 7：事业单位
     *      * 8：业主委员会；
     * @param type
     * @param merchantType
     * @return
     */
    public String companyType(Integer type, MerchantEnum.MERCHANT_TYPE merchantType) {
        // 小微
        if(merchantType == MerchantEnum.MERCHANT_TYPE.PERSONAL){
            return "06";
        }
        // 企业
        String companyType = null;
        switch (type){
            case 5:
                companyType = "07";
                break;
            case 1:
                companyType = "05";
                break;
            case 2:
            case 3:
            case 4:
                companyType = "01";
                break;
            case 8:
            case 6:
                companyType = "03";
                break;
            case 7:
                companyType = "02";
                break;
        }

        return companyType;
    }


    public String licenseType(String code) {
        if (!StringUtils.hasText(code)) {
            return null;
        }
        // 营业执照类型：
        // 1：营业执照
        // 2：营业执照(多证合一)
        // 3：事业单位法人证书
        // 4：社会团体法人登记证书
        // 5：民办非企业单位登记证书
        // 6：基金会法人登记证书
        // 7：宗教活动场所登记证
        // 8：其他证书/批文/证明
        // 9：执业许可证/执业证
        // 10：基层群众性自治组织特别法人统一社会信用代码证
        // 11：农村集体经济组织登记证
        // 12：业主委员会备案证明

        /**
         营业执照: 201
         事业单位法人证书: 218
         民办非企业登记证书: 204
         社会团体法人登记证书: 206
         党政机关批准设立文件/行政执法主体资格证: 219
         个人身份证: 100
         全国法人营业执照(多证合一): 2011
         */
        switch (code) {
            case "1":
                return "201";
            case "2":
                return "2011";
            case "4":
                return "206";
            case "5":
                return "204";
            default:
                return "201";
        }
    }


    public void alipayZftSettleConfirm(String orderNo,String tradeNo, AlipayConfig alipayConfig){
        try{
            PayOrderDO payOrderDO = payOrderService.queryPayOrder(orderNo);
            if(StrUtil.isNotEmpty(tradeNo)){
                payOrderDO.setChannelOrderNo(tradeNo);
                // 缓存交易号，后续回调使用
                redisTemplateService.hSet("pay_system:"+RedisConstants.PAY_ORDER_INFO+":channelOrderNo",tradeNo,payOrderDO,30*24*60*60);
            }
            MerchantAppChannelDO merchantAppChannelDO = merchantApplicationService.queryAppChannelDetail(payOrderDO.getMchChannelCode());
            // 服务商
            AliPayZftChannelParams aliPayChannelParams = JsonUtils.parseObject(merchantAppChannelDO.getAppConfigJson(), AliPayZftChannelParams.class);
            // 获取AlipayClient
            AlipayClient client = initClient(alipayConfig);
            commonTasks.alipayZftSettleConfirm(client,payOrderDO,aliPayChannelParams.getSettleNo(),alipayConfig);
        }catch (Exception e){
            log.error("alipayZftSettleConfirm fail:{}",e);
        }
    }


    public void alipayZftBindProtAccount(String mchChannelCode, AlipayConfig alipayConfig){
        try{
            log.info("支付宝直付通开通默认分账 请求参数:{}", JSONUtil.toJsonStr(alipayConfig));
            // 绑定默认的分账账号
            String accName = alipayConfig.getAccName();
            String accNo = alipayConfig.getAccNo();
            if(StrUtil.isNotEmpty(accName) && StrUtil.isNotEmpty(accNo)){
                // 分账比例
                String accRate = StrUtil.isEmpty(alipayConfig.getAccRate())?"0.06":alipayConfig.getAccRate();
                OpenApiFundAccountBindReq bindReq = new OpenApiFundAccountBindReq();
                bindReq.setName(accName);
                bindReq.setAccountNo(accNo);
                bindReq.setRate(new BigDecimal(accRate));
                bindReq.setMchChannelCode(mchChannelCode);
                bindReq.setFundProcessType(1);
                CommonResult<Void> commonResult = acctAccountAppService.accountBind(bindReq);
                if(commonResult.isSuccess()){
                    log.info("支付宝直付通开通默认分账 成功");
                }else{
                    log.info("支付宝直付通开通默认分账 失败:{}", commonResult.getMsg());
                }
            }
        }catch (Exception e){
            log.error("alipayZftBindProtAccount fail:{}",e);
        }
    }

    public CommonResult<AlipayConfig> aliComplaintConfig(OrderComplaintChannelDO orderComplaintChannelDO, boolean test) {
        String paramsConfig = orderComplaintChannelDO.getBaseConfig();
        if (StringUtils.isEmpty(paramsConfig)) {
            return CommonResult.error(PayResultCode.PAY_CHANNEL_CONFIG_NOT_EXITS);
        }
        try {
            // 配置转换
            AlipayConfig aliPayConfig = JsonUtils.parseObject(paramsConfig, AlipayConfig.class);
            return CommonResult.success(aliPayConfig);
        }
        catch (Exception e) {
            String format = String.format(PayResultCode.PAY_CHANNEL_CONFIG_ERROR.getMsg(), "支付宝");
            return CommonResult.error(PayResultCode.PAY_CHANNEL_CONFIG_NOT_EXITS.getCode(), format);
        }
    }

    public Integer complaintStatusType(String status) {
        /**
         *      * 待处理 0
         *      * 处理中 1
         *      * 已处理完成 2
         *
         *    */

        /**
         用户撤诉: DROP_COMPLAIN
         超时后用户撤诉: DROP_OVERDUE_COMPLAIN
         超时处理完成用户撤诉: DROP_OVERDUE_PROCESSED
         处理完成用户撤诉: DROP_PROCESSED
         超时未处理: OVERDUE
         超时处理完成: OVERDUE_PROCESSED
         部分超时未处理: PART_OVERDUE
         处理完成: PROCESSED
         处理中: PROCESSING
         待处理: WAIT_PROCESS
         */
        switch (status) {
            case "WAIT_PROCESS":
            case "OVERDUE":
            case "PART_OVERDUE":
                return ComplaintStatusType.PENDING.getCode();
            case "PROCESSING":
                return ComplaintStatusType.PROCESSING.getCode();
            case "PROCESSED":
            case "OVERDUE_PROCESSED":
                return ComplaintStatusType.PROCESSED.getCode();
            case "DROP_COMPLAIN":
            case "DROP_OVERDUE_COMPLAIN":
            case "DROP_OVERDUE_PROCESSED":
                return ComplaintStatusType.DISMISSAL.getCode();
        }
        return ComplaintStatusType.PENDING.getCode();
    }


    /**
     *  1 已联系到用户，协商一致，无异议: CONSENSUS_WITH_CLIENT
     *  2 :其他: ORTHER
     *  3:不涉及退款，已针对投诉内容进行整改: RECTIFICATION_NO_REFUND
     *  4:已退款，用户无异议: REFUND
     *  5:已提交证明材料: SUBMIT_PROOF_NOT_CONTACTED
     *  6:其他渠道已退款: OTHER_CHANNEL_REFUND
     */
    public String resultType(Integer type){
        if(type == null){
            return "CONSENSUS_WITH_CLIENT";
        }
        switch (type) {
            case 1:
                return "CONSENSUS_WITH_CLIENT";
            case 2:
                return "ORTHER";
            case 3:
                return "RECTIFICATION_NO_REFUND";
            case 4:
                return "REFUND";
            case 5:
                return "SUBMIT_PROOF_NOT_CONTACTED";
            case 6:
                return "OTHER_CHANNEL_REFUND";
        }
        return "CONSENSUS_WITH_CLIENT";
    }

    /**
     * 花呗分期类型 仅支持传入 3、6、12，其它期数暂不支持
     * @param type
     * @return
     */
    public String hbFqType(Integer type){
        if(type == null){
            return null;
        }
        switch (type) {
            case 1:
                return "3";
            case 2:
                return "6";
            case 3:
                return "12";
        }
        return null;
    }


    /**
     * 商家承担手续费传入 100，用户承担手续费传入 0，仅支持传入 100、0 两种
     * @param type
     * @return
     */
    public String hbFqFeeType(Integer type){
        if(type == null){
            return null;
        }
        switch (type) {
            case 0:
                return "0";
            case 1:
                return "100";
        }
        return null;
    }

    public static void main(String[] args) throws IllegalBlockSizeException, IOException {
        String path = "https://img.hbhlpay.com/image/20241107/2b246318-681e-4505-90af-b59d0ce3effa.png";
        String imgType = FileUtil.extName(path);
        System.out.println(imgType);
        // String text = rsaEncryptOAEP("name",path);
        // System.out.println(text);
        // X509Certificate certificate = PayKit.getCertificate(FileUtil.getInputStream(platPath));
        // String platSerialNo = certificate.getSerialNumber().toString(16).toUpperCase();
        // System.out.println(platSerialNo);
    }

}
